
import 'package:enterprise_v8/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v8/app/components/toast_widget.dart';
import 'package:enterprise_v8/app/core/constans/storage.dart';
import 'package:enterprise_v8/app/core/utils/storage_util.dart';
import 'package:enterprise_v8/app/core/utils/user_manager.dart';
import 'package:enterprise_v8/app/data/api/auth_apis.dart';
import 'package:enterprise_v8/app/data/entities/auth/user_login_entity.dart';
import 'package:enterprise_v8/router/app_pages.dart';

import '../../../app/core/core.dart';

class LoginController extends GetxController {
  /// [lastPressedAt] 退出的倒计时
  DateTime? lastPressedAt;

  /// [textEditingControllerUserName] 用户名
  TextEditingController textEditingControllerUserName = TextEditingController();

  /// [textEditingControllerPassword] 密码
  TextEditingController textEditingControllerPassword = TextEditingController();

  /// [textEditingControllerVerifyCode] 验证码
  TextEditingController textEditingControllerVerifyCode = TextEditingController();

  /// [userNameNode] 用户名焦点
  FocusNode userNameNode = FocusNode();

  /// [passwordNode] 密码焦点
  FocusNode passwordNode = FocusNode();

  /// [verifyCodeNode] 验证码焦点
  FocusNode verifyCodeNode = FocusNode();

  final userNameHasFocus = false.obs;

  final passwordHasFocus = false.obs;

  /// 保存的账号密码
  List<UserLoginEntity> userList = UserManager.getLoginCredentialList();

  RxBool isClick = false.obs;

  final rememberPwd = (StorageUtil.getBool(StorageConstants.rememberLoginCredential) ?? false).obs;

  /// 验证码显示文本(base64)
  final verifyCodeBase64 = '/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA8AKADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9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1H/nja/wDfDf8AxVL/AMJrqX/PC0/74b/4qj20Q9tE70U8VwH/AAm2pf8APC0/74b/AOKpf+E41P8A54Wn/fDf/FUe2iHtonoIqrq//ID1D/r2k/8AQTXFf8Jzqf8AzwtP++G/+KqO58Z6jdWs1u8NqElRkYqrZAIxx81TKtGzFKrGzP/Z'.obs;

  @override
  void onInit() {
    super.onInit();
    if (rememberPwd.value && userList.isNotEmpty) {
      textEditingControllerUserName.text = userList.first.userName;
      textEditingControllerPassword.text = userList.first.passWord;
    }
    userNameNode.addListener(_focusUserNameListener);
    passwordNode.addListener(_focusPassWordListener);
  }

  @override
  void onReady() {
    super.onReady();
    if (UserManager.isLoggedIn) {
      goHome();
    }
  }

  @override
  void dispose() {
    textEditingControllerUserName.dispose();
    textEditingControllerPassword.dispose();
    userNameNode.removeListener(_focusUserNameListener);
    passwordNode.removeListener(_focusPassWordListener);
    super.dispose();
  }

  void _focusUserNameListener() {
    userNameHasFocus.value = userNameNode.hasFocus;
  }

  void _focusPassWordListener() {
    passwordHasFocus.value = passwordNode.hasFocus;
  }

  /// 登录
  void loginDo() async {
    Get.offNamed(Routes.home);
    return;
    UserManager.removeToken();

    // AppLoadingDialog.show();
    if (textEditingControllerUserName.value.text.isEmpty) {
      AppToast.showError('请输入工号/电话号');
      return;
    }
    if (textEditingControllerPassword.value.text.isEmpty) {
      AppToast.showError('请输入密码');
      return;
    }
    isClick.value = true;
    final result = await AuthApis.login(
      username: textEditingControllerUserName.value.text,
      password: textEditingControllerPassword.value.text,
    ).execute();

    result.onSuccess((result) {
      /// 保存token
      if (result.data != null) {
        UserManager.saveUser(result.data!);
        UserManager.saveToken('${result.data!.tokenType} ${result.data!.accessToken}');
        if (rememberPwd.value) {
          UserManager.saveLoginCredential(
            textEditingControllerUserName.value.text,
            textEditingControllerPassword.value.text,
          );
        }
        goHome();
      } else {
        AppToast.showError('用户数据为空');
        // goHome();
      }
    });

    result.onError((result) {
      isClick.value = false;
    });
  }

  /// 重置账号
  void reset() async {
    textEditingControllerUserName.clear();
    textEditingControllerPassword.clear();
  }

  /// 记住密码
  void onRememberPwdChanged(bool? value) {
    value ??= false;
    rememberPwd.value = value;
    StorageUtil.setBool(StorageConstants.rememberLoginCredential, value);
  }

  /// 忘记密码(弹窗提示)
  void forgetPwd() {
    Get.dialog(ExitTips(
      content: '若忘记密码，请联系系统管理员，电话1xxxxxxxxxx。', onConfirmed: () {},
    ));
  }

  /// 登录完跳转
  void goHome() {
    // 是否需要验证
    if(false) {
      Get.toNamed(Routes.verify);
      isClick.value = false;
    } else {
      Future.delayed(const Duration(milliseconds: 2000), () {
        isClick.value = false;
      });
      Get.offNamed(Routes.home);
      // AppToast.showSuccess('登录成功');
    }


  }

  /// 判断是否退出页面
  bool isPopPage() {
    if (lastPressedAt == null || DateTime.now().difference(lastPressedAt!) > const Duration(seconds: 1)) {
      return false;
    } else {
      return true;
    }
  }

  /// 移除历史账号
  void removeHistoryUser(UserLoginEntity user) {
    UserManager.removeLoginCredential(user.userName);
    userList = UserManager.getLoginCredentialList();
    Get.back();
    update();
  }

  /// 选择历史账号
  void selectHistoryUser(UserLoginEntity user) {
    textEditingControllerUserName.text = user.userName;
    textEditingControllerPassword.text = user.passWord;
  }

  /// 获取验证码
  void getVerifyCode() async {
    // final result = await AuthApis.getVerifyCode().execute();
    // result.onSuccess((result) {
    //   if (result.data != null) {
    //     verifyCodeBase64.value = result.data!;
    //   }
    // });
  }

  /// 刷新验证码
  void refreshVerifyCode() {
    getVerifyCode();
  }

}
